package com.basiclib.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Point
import android.net.Uri
import android.provider.Settings
import androidx.core.content.pm.PackageInfoCompat
import android.util.DisplayMetrics
import android.view.inputmethod.InputMethodManager
import org.jetbrains.anko.inputMethodManager
import org.jetbrains.anko.windowManager


fun Context.versionName(): String {
    var version = "1.0.0"
    try {
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        version = packageInfo.versionName
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return version
}
fun Context.versionCode(): Long {
    var version = 0L
    try {
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        version = PackageInfoCompat.getLongVersionCode(packageInfo)
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return version
}

fun Context.gotoPermissionSettings(newTask: Boolean) {
    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    //创建一个新栈存放，用户在系统设置授予权限后，会导致返回后不会重新创建当前Activity，不推荐这种做法
    if (newTask) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    intent.data = Uri.fromParts("package", packageName, null)
    startActivity(intent)
}

fun Context.displayMetrics(): Point {
    val dm = DisplayMetrics()
    val display = this.windowManager.defaultDisplay
    display.getMetrics(dm)
    val mDisplayWidth = dm.widthPixels
    val mDisplayHeight = dm.heightPixels
    return Point(mDisplayWidth, mDisplayHeight)
}

fun Activity.hideSoftKeyword() {
    if (inputMethodManager.isActive() && currentFocus != null) {
        if (currentFocus!!.windowToken != null) {
            inputMethodManager.hideSoftInputFromWindow(
                currentFocus!!.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}